import React, { Component } from 'react';
import { View, Text, StyleSheet, ScrollView, Modal, Image, TouchableOpacity, PixelRatio } from 'react-native';
import { GLOBAL } from '../../config/global';
import { style } from '../../theme/style';
import HTTP from "../../utils/http";
import { API, API_GENERATE } from '../../config/api';
import { PageStatusIndex } from '../page-status/PageStatusIndex';
import StorageHelper from '../../utils/storageHelper';
import Utils from '../../utils/utils';

const LETTER = [{ name: 'A' }, { name: 'B' }, { name: 'C' }, { name: 'D' }, { name: 'E' }, { name: 'F' }, { name: 'G' },
{ name: 'H' }, { name: 'I' }, { name: 'J' }, { name: 'K' }, { name: 'R' }, { name: 'M' }, { name: 'N' }, { name: 'O' },
{ name: 'P' }, { name: 'Q' }, { name: 'R' }, { name: 'S' }, { name: 'T' }, { name: 'U' }, { name: 'V' }, { name: 'W' },
{ name: 'X' }, { name: 'Y' }, { name: 'Z' }];


const scale = GLOBAL.SCALE;


export class OriginalAddress extends Component {
    constructor(props) {
        super(props);
        this.state = {
            status: 'loading',
            typeCountries: 0, // 类型, 0中国/1外国
        }
        this.arrNum = [];
        this.count = 0; //计数器
        this.letterList = JSON.parse(JSON.stringify(LETTER));
        this.addressList = [];
        this.historyArr = [];
        this.storageType = "addressHistory";
    }
    componentWillMount = async () => {
        let { params } = this.props || {};
        if (params && params.tradeType === "O") {
            this.storageType = "addressHistoryOut";
        }

        await this._getData();
        this.historyArr = await StorageHelper.get(this.storageType);
        this.historyArr = JSON.parse(this.historyArr) || [];
        this.setState({ ls: true });
    }

    _getData = async () => {
        let { params } = this.props || {};
        let respones = await HTTP.GET(API_GENERATE(API.ORIGINAL_ADDRESS), params);
        if (respones && (respones.homeAreaInfoList || respones.abroadAreaInfoList)) {
            await this._modifyData({ ...respones }); // 处理数据
            this.setState({
                status: 'data'
            })
        } else {
            this.setState({ status: 'empty' });
        }
    }

    //修改数据
    _modifyData = (data) => {
        let { homeAreaInfoList, abroadAreaInfoList } = data || {};
        return new Promise((resolve) => {
            //处理国内数据
            this.homeAreaInfoListArr = this._letterSort(homeAreaInfoList) || [];
            console.log("中国-处理完之后的数据", this.homeAreaInfoListArr)
            //处理国外数据
            this.abroadAreaInfoListArr = this._letterSort(abroadAreaInfoList) || [];
            console.log("外国-处理完之后的数据", this.abroadAreaInfoListArr)
            resolve();
        })
    }


    // 国家按字母排序
    _letterSort = (listData) => {
        let resultArr = [];
        this.letterList.forEach((item) => {
            let lsData = { title: item.name, data: [] };
            listData && listData.forEach((items) => {
                if (items.initial === item.name) {
                    lsData.data.push(items);
                }
            })
            if (lsData.data.length) {
                resultArr.push(lsData);
            }
        })
        return resultArr;
    }


    //点击字母 快速定位
    _clickLetter = (letter) => {
        let { letterY, name } = letter || {};
        if (letterY === undefined) { console.log("name:", name); return; }
        this.scrollView.scrollTo({ x: 0, y: letterY, animated: true }, 1);
    }

    //获取 每个字母的位置
    _layout = (e, title) => {
        this.arrNum.push({ y: e.layout.y, height: e.layout.height, id: title })
        this.letterList.map(item => {
            if (item.name === title) {
                item.letterY = e.layout.y;
            }
            return item
        })
        this.count++;
        if (this.count === this.addressList.length) {
            this.setState({
                ls: true
            })
        }
    }

    //切换国家
    _toggleCountries = typeIndex => {
        let { typeCountries } = this.state;
        if (typeCountries === typeIndex) return;
        this.arrNum = [];// 切换重新记录
        this.count = 0; // 清空计数器
        this.letterList = JSON.parse(JSON.stringify(LETTER));
        //this.scrollView.scrollTo({ x: 0, y: 0, animated: true }, 1);
        this.setState({
            typeCountries: typeIndex
        })
    }

    //选择后回调
    _selectAddress = async (selectAddress, isHistory) => {
        let { closeModal, addressCallback } = this.props || {};
        closeModal && closeModal();
        addressCallback(selectAddress);
        if (!isHistory) {
            let lsArr = await StorageHelper.get(this.storageType);
            lsArr = JSON.parse(lsArr) || [];
            let repeatIndex = -1;
            lsArr.forEach((item, index) => {
                if (item.makeAreaId === selectAddress.makeAreaId) {
                    repeatIndex = index;
                }
            })
            if (repeatIndex != -1) lsArr.splice(repeatIndex, 1);
            lsArr.unshift(selectAddress);
            if (lsArr.length > 6) lsArr.length = 6;
            StorageHelper.set(this.storageType, JSON.stringify(lsArr));
        }
    }

    _clearHistory = async () => {
        await StorageHelper.remove(this.storageType, () => {
            this.historyArr = [];
            this.setState({ ls: true })
        });
    }

    render() {
        let { status, typeCountries } = this.state;
        let { modalVisible, closeModal, params } = this.props || {};
        this.addressList = typeCountries === 0 ? this.homeAreaInfoListArr : this.abroadAreaInfoListArr;
        return <View style={styles.container}>
            <Modal
                animationType={"fade"}
                transparent={true}
                onRequestClose={() => { console.log(1) }}
                visible={modalVisible}>
                <View style={styles.scollContainer}>
                    <View style={styles.scollBox}>
                        <View style={[styles.header, styles.pd]}>
                            <Text style={styles.headerTitle}>请选择所在地区</Text>
                            <TouchableOpacity onPress={() => { closeModal && closeModal() }}>
                                <Image style={styles.imgStyle} source={require("../../imgs/close.png")} />
                            </TouchableOpacity>
                        </View>
                        <View style={[styles.pd, (this.historyArr && this.historyArr.length > 0) ? null : { marginBottom: 50 * scale }]}>
                            <View style={styles.togger}>
                                <Text onPress={() => { this._toggleCountries(0) }} style={[styles.toggerText, typeCountries === 0 ? styles.toggerTextActive : null]}>中 国</Text>
                                <Text onPress={() => { this._toggleCountries(1) }} style={[styles.toggerText, typeCountries === 1 ? styles.toggerTextActive : null]}>海 外</Text>
                            </View>
                            {
                                (this.historyArr && this.historyArr.length) ? <View style={styles.hotBox}>
                                    <View style={styles.historyHead}>
                                        <Text style={styles.hotTitle}>历史记录</Text>
                                        <Text style={styles.historyClear} onPress={this._clearHistory}>清空历史</Text>
                                    </View>
                                    <View style={styles.hotBody}>
                                        {
                                            this.historyArr.map((items, indexs) => {
                                                return <Text onPress={() => { this._selectAddress(items, true) }} key={indexs} style={styles.hotItem}>{items.shortName}</Text>
                                            })
                                        }
                                    </View>
                                </View> : null
                            }
                        </View>
                        <View style={[styles.body, styles.pd]}>
                            {
                                status === "data" ? <ScrollView style={styles.scrollView} ref={scrollView => this.scrollView = scrollView}>
                                    {
                                        this.addressList && this.addressList.map((item, index) => {
                                            return (
                                                <View onLayout={({ nativeEvent: e }) => this._layout(e, item.title)} style={styles.scrollItem} key={index}>
                                                    <Text style={styles.scrollTitle}>{item.title}</Text>
                                                    <View style={styles.scrollChild}>
                                                        {
                                                            item.data && item.data.map((items, indexs) => {
                                                                return <TouchableOpacity onPress={() => { this._selectAddress(items) }} key={indexs}><Text style={styles.scrollChildItem}>{items.shortName}</Text></TouchableOpacity>
                                                            })
                                                        }
                                                    </View>
                                                </View>
                                            )
                                        })
                                    }
                                </ScrollView> : <PageStatusIndex status={status} emptyText={'暂无数据'} />
                            }
                        </View>
                    </View>
                    <View style={styles.letterBox}>
                        {this.letterList && this.letterList.map((item, index) => {
                            return Utils.isEmpty(item.letterY) ? null : <TouchableOpacity onPress={() => { this._clickLetter(item) }} key={index} style={styles.letterItemBox}><Text style={styles.letterItem} key={index}>{item.name}</Text></TouchableOpacity>
                        })}
                    </View>
                </View>
            </Modal>
        </View>
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'row'
    },
    pd: {
        paddingHorizontal: 25 * scale
    },
    scollContainer: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, .3)',
        justifyContent: 'flex-end'
    },
    scollBox: {
        width: "100%",
        //height: "80%",
        backgroundColor: "#fff",
        justifyContent: 'flex-end',
    },
    header: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingVertical: 20 * scale
    },
    headerTitle: {
        fontSize: 18 * scale
    },
    imgStyle: {
        width: 22 * scale,
        height: 22 * scale,
        marginRight: 20 * scale
    },
    togger: {
        flexDirection: 'row'
    },
    toggerText: {
        fontSize: 15 * scale,
        marginRight: 20 * scale
    },
    toggerTextActive: {
        color: style.color.themeColor,
    },
    hotBox: {
        marginTop: 10 * scale,
        marginRight: 30 * scale
    },
    hotTitle: {
        fontSize: 14 * scale,
        color: '#666'
    },
    hotBody: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        marginTop: 5 * scale,
        height: 70 * scale,
        overflow: 'hidden'
    },
    hotItem: {
        fontSize: 13 * scale,
        color: '#555',
        marginVertical: 8 * scale,
        marginRight: 25 * scale,
        backgroundColor: '#eee',
        height: 20 * scale,
        lineHeight: 20 * scale,
        paddingHorizontal: 10 * scale
    },
    body: {
        flexDirection: 'row',
        height: 350 * scale
    },
    letterBox: {
        backgroundColor: '#eee',
        alignItems: 'center',
        justifyContent: 'center',
        position: 'absolute',
        right: 8 * scale,
        bottom: 30 * scale,
        borderRadius: 5 * scale,
    },
    letterItemBox: {
        paddingHorizontal: 2 * scale,
        paddingVertical: 2 * scale
    },
    letterItem: {
        fontSize: 12 * scale
    },
    scrollTitle: {
        color: '#000',
        fontSize: 16 * scale,
        backgroundColor: '#efefef',
        paddingLeft: 5 * scale
    },
    scrollChild: {
        //borderTopWidth: 1 / PixelRatio.get(),
        //borderStyle: 'solid',
        //borderTopColor: style.color.border,
        //marginTop: 5 * scale,
        marginVertical: 5 * scale,
        paddingLeft: 10 * scale
    },
    scrollChildItem: {
        lineHeight: 35 * scale
    },
    scrollView: {
        marginTop: 10 * scale,
        marginRight: 35 * scale,
        paddingBottom: 20 * scale,
    },
    historyHead: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        marginTop: 10 * scale
    },
    historyClear: {
        fontSize: 13 * scale,
        marginLeft: 10 * scale,
        color: style.color.themeColor
    }
})